package org.xiaojl.modules.drp.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.xiaojl.modules.drp.entity.DrpProductType;
import org.xiaojl.modules.drp.mapper.DrpProductTypeMapper;
import org.xiaojl.modules.drp.service.DrpProductTypeService;
import org.xiaojl.utils.ToolUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * <p>
 * 产品类型 服务实现类
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-06
 */
@Service
public class DrpProductTypeServiceImpl extends ServiceImpl<DrpProductTypeMapper, DrpProductType> implements DrpProductTypeService {

	@Override
	public String selectAllTree(String pid) {
		List<DrpProductType> list = this.selectList(
				new EntityWrapper<DrpProductType>().orderBy("createTime", true)
				);
		StringBuffer strJson = new StringBuffer();
		recursionTree(pid, strJson, list,true);
		return strJson.toString();
	}

	private void recursionTree(String pid, StringBuffer buffer,
			List<DrpProductType> list, boolean first) {
		if (first) {
			buffer.append("<ul class=\"tree treeFolder expand \" >");
		} else {
			buffer.append("<ul>");
		}
		List<DrpProductType> listMap = getSonListByPid(pid, list);
		for (DrpProductType map : listMap) {
			String id = map.getId().toString();// id
			String name = map.getName();// 名称
			String isLeaf = map.getIsLeaf().toString();// 是否叶子科目
			buffer.append("<li><a onclick=\"onClickMenuNode('" + id + "')\" href=\"#\" target=\"ajax\" rel=\"jbsxBox\"  value='" + id + "' id='" + id + "'>" + name + "</a>");
			if (!isLeaf.equals("0")) {
				recursionTree(id, buffer, list, false);
			}
			buffer.append("</li>");
		}
		buffer.append("</ul>");
	}

	private List<DrpProductType> getSonListByPid(String pid, List<DrpProductType> list) {
		List<DrpProductType> sonMenuList = new ArrayList<DrpProductType>();
		for (DrpProductType menu : list) {
			if (menu != null) {
				String parentId = menu.getPid()+"";// 父id
				if (parentId.equals(pid)) {
					sonMenuList.add(menu);
				}
			}
		}
		return sonMenuList;
	}

	@Override
	public void insertWithCacade(DrpProductType entity) {
		DrpProductType p = this.selectById(entity.getPid());
		if(ToolUtil.isNotEmpty(p)){
			p.setIsLeaf(1);
			this.updateById(p);
		}
		
		this.insert(entity);
	}
	
}
